var UserManager = function(){
	var userGridObj = null;
	var blockeduserGridObj = null;
	var userAddValidator = null;
	var userPassWdValidator = null;
	var roleZtreeObj = null;
	var areaZtreeObj = null;
	function initUserList(){
		if(userGridObj == null){
			userGridObj = $.fn.bsgrid.init('userListTable', {
	            url:contextPath+"/sys/user/userlist.htm",
	            pageSizeSelect: true,
	            stripeRows: true,
	            rowSelectedColor:false,
	            pageSize: 10,
				complete:function(){
					$("#userListTable_pt_outTab").width($("#userListTable").width());
				}
				
	        });
		}else{
			userGridObj.refreshPage();
		}
	}
	function initUserBlockedList(){
		if(blockeduserGridObj == null){
			blockeduserGridObj =  $.fn.bsgrid.init('userBlockedTable', {
	            url:contextPath+"/sys/user/blockedlist.htm",
	            pageSizeSelect: true,
	            stripeRows: true,
	            rowSelectedColor:false,
	            pageSize: 10,
				complete:function(){
					$("#userBlockedTable_pt_outTab").width($("#userBlockedTable").width());
				}
				
	        });
		}else{
			blockeduserGridObj.refreshPage();
		}
	}
	function openUserEditDialog(userId){
		var dialogTitle = userId == '' ?'新增用户':'编辑用户'; 
		DialogUtils.open({
		    title: dialogTitle,
		    area: ['700px', '500px'],
		    fix: false, //不固定
		    maxmin: true,
		    content: contextPath+'/sys/user/edit.htm?userId='+userId,
		    btn: ['保存', '取消'],
		    yes: function(index, layero){
		    	 userSave(index, layero);
		    },cancel: function(index){
		    }
		});
	}
	function userSave(index, layero){
		var body = DialogUtils.getChildFrame('body', index);
		var editform = body.find("#editForm");
		var pawdform = body.find("#passwordForm");
		var tab = body.find("#myTab");
		if(tab.find("li").eq(0).hasClass("active")){
			userAddValidator =editform.validate({
				rules: {
					userName:{required: true},
					name:{required: true},
					password:{required: true,notSpecial:true},
					confirmPassword:{required: true,notSpecial:true,equalTo:body.find("#password")}
				}
			});
			userAddValidator.form();
			if (!userAddValidator.valid()) {
				return false;
			}
			var userDTO={
					"userId":body.find("#id").val()==""?null:body.find("#id").val(),
					"userName":body.find("#userName").val(),
					"name":body.find("#name").val(),
					"password":body.find("#password").val(),
					"blocked":body.find("input[name='blocked']:checked").val(),
					"userAuthCode":body.find("#userAuthCode").val()
			};
			SysUserController.saveUserInfo(userDTO,function(data){
				if(data != null){
					body.find("#id").val(data.userId);
					body.find("#userId").val(data.userId);
					body.find("#userRemakeName").text(data.name);
					body.find("#passwordForm").show();
					userGridObj.refreshPage()
					Message.success('保存成功！');
				}
			});
		}
		if(tab.find("li").eq(1).hasClass("active")){
			var areaId = DialogUtils.getChildFrameWindow(layero).getCheckAreaNodeId();
			SysAreaController.addUserIntoAreaByUserId(areaId,body.find("#id").val(),function(data){
				if(data){
					Message.success('保存成功！');
				}
			});
		}
		if(tab.find("li").eq(2).hasClass("active")){
			var roleIds = DialogUtils.getChildFrameWindow(layero).getCheckRoleNodeId(); 
			SysUserController.saveUserOwnRoles(body.find("#id").val(),roleIds,function(data){
				if(data){
					Message.success('保存成功！');
				}
			});
		}
		if(tab.find("li").eq(3).hasClass("active")){
			userPassWdValidator =pawdform.validate({
				rules: {
					newpassword:{required: true,notSpecial:true},
					rpassword:{required: true,notSpecial:true,equalTo:body.find("#newpassword")}
				}
			});
			userPassWdValidator.form();
			if (!userPassWdValidator.valid()) {
				return false;
			}
			
			var userPaswd = {
					"userId":body.find("#userId").val()==""?null:body.find("#userId").val(),
					"password":	body.find("#newpassword").val()
			}
			
			SysUserController.saveUserInfo(userPaswd,function(data){
				if(data != null){
					Message.success('密码修改成功！');
				}
			});
			
		}

		
	}
	return {
		initUserPage:function(){
			$('#myTab a:first').tab('show');//初始化显示哪个tab
			$("#allUser").click(function(){
				initUserList();
			});
			$("#blockedUser").click(function(){
				initUserBlockedList();
			});
			$("#allUser").click();
		},
		operateUserEdit:function(record, rowIndex, colIndex, options) {
	        return '<a href="#" onclick="UserManager.userEdit(\''+userGridObj.getRecordIndexValue(record, 'userId')+'\');">编辑</a>';
	    },
	    operateUserUnBlocked:function(record, rowIndex, colIndex, options) {
	        return '<a href="#" onclick="UserManager.userUnBlocked(\''+userGridObj.getRecordIndexValue(record, 'userId')+'\');">解除锁定</a>';
	    },
	    userEdit:function(userId){
	    	openUserEditDialog(userId);
	    },
	    userUnBlocked:function(userId){
	    	Message.confirm('您确定要解锁该用户？', 
	    	     function(){
	    		SysUserController.unBlockedUpdateByUserId(userId,function(data){
		    		if(data){
		    			Message.success('解除锁定成功！');
		    			blockeduserGridObj.refreshPage();
		    		}
		    	});
	    	}, function(){
	    	});

	    },
	    initUserAddDialog:function(){
	    	$('#myTab a:first').tab('show');
			$("#userPasswd").click(function(){
				if($("#userId").val() == ""){
					Message.tips('请先保存用户信息', '#userPasswd', {layout:'up'});
				}
			});
	    },
	    deleteUser:function(type){
	    	var gridObj = null;
	    	if(type == 'user'){
	    		gridObj = userGridObj;
	    	}else if(type == 'blocked'){
	    		gridObj = blockeduserGridObj;
	    	}
	    	var array = AppUtils.gridCheckColumnValue(gridObj,"userId"); 
	    	if(array.length ==0){
	    		Message.error('你还没有选择要删除的用户！');
	    		return false;
	    	}
	    	Message.confirm("确认要删除该用户吗？",function(){
	    		SysUserController.removeUserByUserIds(array,function(data){
					if(data){
						Message.success('删除成功');
						gridObj.refreshPage();
					}else{
						Message.error('删除失败');
					}
				});
	    	});
	    	
	    },
	    initRoleTree:function(){
	    	if($("#id").val() == ""){
	    		$("#roleTreeEdit").hide();
				Message.tips('请先保存用户信息', '#userRole', {layout:'up'});
				return false;
	    	}
	    	$("#roleTreeEdit").show();
	    	var userId = $("#id").val();
	    	SysUserController.showUserOwnRoles(userId,function(retMap){
	    		if(retMap){
	    			var roleTree = retMap["roleTree"];
	    			var ownRoles = retMap["ownRoles"];
	    			
	    			ZtreeUtil.initTree("roleTree",roleTree,{
					},{
						data:{
							key:{
								name: "text",
				    			url: null
							}
						},check: {
							enable: true
						}
					});
	    			roleZtreeObj =  ZtreeUtil.getZtreeObj('roleTree');
	    			roleZtreeObj.expandNode(ZtreeUtil.getBaseNode('roleTree'), true, false, true);
					if(ownRoles.length !=0){
						for (var i=0; i<ownRoles.length;  i++) {
							roleZtreeObj.checkNode(roleZtreeObj.getNodeByParam("id",ownRoles[i] , null), true, true);
						}
					}
					
	    		}
	    	});
	    },
	    initAreaTree:function(){
	    	if($("#id").val() == ""){
	    		$("#areaTreeEdit").hide();
				Message.tips('请先保存用户信息', '#userArea', {layout:'up'});
				return false;
	    	}
	    	$("#areaTreeEdit").show();
	    	var userId = $("#id").val();
	    	SysUserController.showUserOwnArea(userId,function(retMap){
	    		if(retMap){
	    			var areaTree = retMap["areaTree"];
	    			var userDTO = retMap["userDTO"];
	    			
	    			ZtreeUtil.initTree("areaTree",areaTree,{
	    				onClick: function(event, treeId, treeNode){
	    					if(!treeNode.checked){
	    						areaZtreeObj.checkNode(treeNode, true, false);
	    					}else{
	    						areaZtreeObj.checkNode(treeNode, false, false);
	    					}
	    					
						}
					},{
						data:{
			    			simpleData:{
			    				enable:true,
			    				idKey:"id",
			    				pIdKey:"pId",
			    				rootPId:null
			    				},
			    		key: {
			    			name: "text",
			    			url: null
			    			}
			    		},
						check: {
							enable: true,
							chkStyle: "radio",
							radioType: "all"
						}
					});
	    			areaZtreeObj =  ZtreeUtil.getZtreeObj('areaTree');
	    			areaZtreeObj.expandAll(true);
	    			var baseNode = areaZtreeObj.getNodeByParam("id", "VirtualBaseTree", null);
	    			areaZtreeObj.setChkDisabled(baseNode, true);
					if(userDTO !=null && userDTO.userAreaId){
						var checkNode = areaZtreeObj.getNodeByParam("id",userDTO.userAreaId, null);
						areaZtreeObj.checkNode(checkNode, true, false);
					}
					
	    		}
	    	});
	    },
	    getCheckRoleNodeId:function(){
	    	var nodes = roleZtreeObj.getCheckedNodes(true);
			var roleIds =new Array();
			$.each(nodes,function(index,element){
				if(element.type == "role"){
					roleIds.push(element.id);
				}
			});
			return roleIds;
	    },
	    getCheckAreaNodeId:function(){
	    	var nodes = areaZtreeObj.getCheckedNodes(true);
	    	var areaId = null;
			$.each(nodes,function(index,element){
				if(element.type == "area"){
					areaId =element.id;
				}
			});
			return areaId;
	    }
	    
	    
	};
}();